<?php

/**
 * Implements a simple register. It is structure in rows and columns as table.
 * @author Pablo
 * @since 1.0
 */

class blgRegister {
	protected $table;
	protected $num_rows;
	protected $num_cols;
	protected $keys;
	protected $makeFirstColUnique;
	
	function __construct(){
		$this->table= array();
		$this->num_rows= 0;
		$this->num_cols= 0;
		$this->keys= array();
		$this->makeFirstColUnique= FALSE;
	}
	
	/**
	 * Register new row data
	 * @param array $data
	 * @return Boolean
	 * @author Pablo
	 */
	public function register($data){
		if(is_array($data)){
			//Set or check the number of columns				
			if($this->num_rows>0){
				if($this->num_cols!=count($data)){ 
					$caller= caller_info();
					trigger_error("Inserting a ".count($data)." columns row, expecting to be a ".$this->num_cols." columns row at line ".$caller->line." in ".$caller->file, E_USER_WARNING);
					return FALSE;
				}
			}else{				
				$this->num_cols= count($data);				
			}			
			
			//Add data to the register
			if($this->makeFirstColUnique){
		
				$pos= array_search(reset($data), $this->keys);
				if($pos===FALSE){
					$this->table[]= $data;
					$this->keys[]= current($data);
					$this->num_rows++;
				}
				else{
					$this->table[$pos]= $data;
				}
			}
			else{
				//ADD ALWAYS DATA
				$this->table[]= $data;
				$this->num_rows++;
			}
			
			return TRUE;
		}

		return FALSE;
	}
	
	/**
	 * Counts register rows number
	 * @return Integer
	 * @author Pablo
	 * @since 1.0
	 */
	public function count_rows(){
		return $this->num_rows;
	}
	
	/**
	 * Counts register columns number
	 * @return Integer
	 * @author Pablo
	 * @since 1.0
	 */	
	public function count_cols(){
		return $this->num_cols;
	}

	/**
	 * MAGIC FUNCTION wich returns a human readable text description of the register
	 * @return String
	 * @author Pablo
	 * @since 1.0
	 */	
	public function __toString(){
		$str= '';
		foreach($this->table as $row){
			$str.='| '.implode(' | ', $row)." |\n";
		}
		return $str;
	}	
}
